<template>
  <!-- {{menu}} -->
  <el-container class="ysjf-home">
    <el-aside class="sidebar" width="260px">
      <div class="logo">
        <span class="logo-icon">🏭</span>
        <span class="logo-text">MES制造执行系统</span>
      </div>

      <div class="menu-section">
        <el-menu
          :default-active="route.path"
          class="nav-menu"
          background-color="transparent"
          text-color="#cbd5f5"
          active-text-color="#fff"
          router
          @select="handleMenuSelect"
        >
          <el-menu-item index="indexeach">
            <span class="menu-icon">🏠</span>
            首页
          </el-menu-item>

          <el-sub-menu
            v-for="item in menu"
            :key="item.index"
            :index="item.index"
          >
            <template #title>
              <span class="menu-icon">📂</span>
              {{ item.label }}
            </template>

            <template v-for="subItem in item.children || []" :key="subItem.index">
              <el-menu-item
                v-if="!subItem.children || subItem.children.length === 0"
                :index="subItem.index"
              >
                {{ subItem.label }}
              </el-menu-item>
              <el-sub-menu v-else :index="subItem.index">
                <template #title>{{ subItem.label }}</template>
                <el-menu-item
                  v-for="thirdItem in subItem.children"
                  :key="thirdItem.index"
                  :index="thirdItem.index"
                >
                  {{ thirdItem.label }}
                </el-menu-item>
              </el-sub-menu>
            </template>
          </el-sub-menu>
        </el-menu>
      </div>
    </el-aside>

    <el-container class="content-container">
      <el-header class="header">
        <div class="header-container">
          <div class="page-title">
            <el-breadcrumb separator="">
              <el-breadcrumb-item
                v-for="item in breadcrumbs"
                :key="item.path"
                :to="item.path"
              >
                <span class="breadcrumb-chip" :class="{ 'is-current': item.isCurrent }">
                  <el-icon v-if="item.icon" class="breadcrumb-icon">
                    <component :is="item.icon" />
                  </el-icon>
                  <span>{{ item.label }}</span>
                </span>
              </el-breadcrumb-item>
            </el-breadcrumb>
            <p class="welcome-text">欢迎回来，{{ userNameDisplay }}</p>
          </div>
          <div class="header-right">
            <el-dropdown trigger="click" @command="handleUserCommand" placement="bottom-end">
              <span class="user-chip dropdown-trigger">
                <span class="avatar-circle">
                  <span v-if="!userAvatar" class="avatar-text">{{ avatarText }}</span>
                  <img v-else :src="userAvatar" alt="头像" class="avatar-img" />
                  <el-icon v-if="!userAvatar && !avatarText" class="avatar-icon"><User /></el-icon>
                </span>
                <span class="user-name">{{ userNameDisplay }}</span>
                <el-icon class="dropdown-arrow"><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu class="user-dropdown-menu">
                  <div class="dropdown-header">
                    <span class="dropdown-avatar">
                      <span v-if="!userAvatar" class="avatar-text">{{ avatarText }}</span>
                      <img v-else :src="userAvatar" alt="头像" class="avatar-img" />
                      <el-icon v-if="!userAvatar && !avatarText" class="avatar-icon"><User /></el-icon>
                    </span>
                    <div class="dropdown-user-info">
                     
                      <div class="dropdown-user-role" v-if="userRole">{{ userRole }}</div>
                    </div>
                  </div>
                  <el-dropdown-item command="profile" class="dropdown-item">
                    <el-icon class="item-icon"><Setting /></el-icon>
                    <span>个人设置</span>
                  </el-dropdown-item>
                  <el-dropdown-item divided command="logout" class="dropdown-item logout-item">
                    <el-icon class="item-icon"><SwitchButton /></el-icon>
                    <span>退出登录</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>

      <el-main>
        <div class="content-wrapper">
          <RouterView />
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, type Component } from 'vue'
import {
  ElHeader,
  ElMenu,
  ElSubMenu,
  ElMenuItem,
  ElMenuItemGroup,
  ElCarousel,
  ElCarouselItem,
  ElButton,
  ElMain,
  ElCard,
  ElImage,
  ElInput,
  ElLink,
  ElFooter,
  ElIcon,
  ElMessageBox,
  ElBreadcrumb,
  ElBreadcrumbItem
} from 'element-plus'
import {
  Search,
  User,
  SwitchButton,
  ArrowDown,
  House,
  CollectionTag,
  Tickets,
  Collection,
  UserFilled,
  Avatar,
  Briefcase,
  OfficeBuilding,
  Setting,
  Histogram,
  Postcard,
  Printer,
  Calendar
} from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import https from '@/Http/http'
import axios from 'axios'

// 导航激活状态 + 搜索框数据
const activeNav = ref('home')
const searchText = ref('')
const menu: any = ref([])
const userName = ref('')
const userRole = ref('')
const userAvatar = ref('')
const userNameDisplay = computed(() => userName.value || '用户')
// 头像文字（用户名首字母）
const avatarText = computed(() => {
  if (userName.value) {
    return userName.value.charAt(0).toUpperCase()
  }
  return 'U'
})
const breadcrumbMap: Record<string, string> = {
  index: '控制台',
  indexeach: '首页',
  about: '关于',
  ceshigetlist: '测试列表',
  codingRule: '编码规则',
  UserView: '用户管理',
  RoleView: '角色管理',
  JobView: '岗位管理',
  OrganView: '组织架构',
  GetUserIdView: '个人设置',
  WorkTeamList: '班组列表',
  WorkTeamTypeList: '班组类型',
  WorkingciList: '工作中心',
  CustList: '客户管理',
  SupplierList: '供应商管理',
  WoekingSchedule: '排班计划',
  WorkingCalendarList: '工作日历',
  AProduction_PlanView: '生产计划',
  AProduction_OrderView: '生产工单',
  AWork_Order_TaskShowView: '工单任务',
  AWork_Quality_InspectionView: '报工质检',
  AWork_ReportView: '报工记录'
}
const breadcrumbIcons: Partial<Record<string, Component>> = {
  index: House,
  indexeach: House,
  about: CollectionTag,
  ceshigetlist: Tickets,
  codingRule: Collection,
  UserView: UserFilled,
  RoleView: Avatar,
  JobView: Briefcase,
  OrganView: OfficeBuilding,
  GetUserIdView: Setting,
  WorkTeamList: Histogram,
  WorkTeamTypeList: CollectionTag,
  WorkingciList: Collection,
  CustList: Postcard,
  SupplierList: Printer,
  WoekingSchedule: Calendar,
  WorkingCalendarList: Calendar,
  AProduction_PlanView: Setting,
  AProduction_OrderView: Setting,
  AWork_Order_TaskShowView: Setting,
  AWork_Quality_InspectionView: Setting,
  AWork_ReportView: Setting
}
const breadcrumbs = computed(() => {
  const matched = route.matched.filter(item => item.name && item.path !== '/')
  if (!matched.length) {
    return [
      {
        label: '首页',
        path: '/indexeach',
        icon: breadcrumbIcons.indexeach,
        isCurrent: true
      }
    ]
  }
  return matched.map((item, index) => {
    const name = typeof item.name === 'string' ? item.name : ''
    return {
      label: breadcrumbMap[name] || (item.meta?.title as string) || name || item.path,
      path: item.path,
      icon: breadcrumbIcons[name],
      isCurrent: index === matched.length - 1
    }
  })
})
const READ_BASE_URL = 'http://localhost:5157'

const router = useRouter();
const route = useRoute();

onMounted(() => {
  ShowMenu()
  fetchUserProfile()
})

const ShowMenu = () => {
  https.Reads.get("/RBAC/BindPer")
    .then(res => {
      console.log(res)

      menu.value = res.data.data;
    })
}

// 产品数据
const productImage = ref('https://ts1.tc.mm.bing.net/th/id/OIP-C.bxA8Xn8wnbcWY2Q47jWnXwHaEt?w=247&h=211&c=8&rs=1&qlt=90&o=6&dpr=1.5&pid=3.1&rm=2');


const ceshigetlist = router.push("")

// 菜单选择事件（可添加路由跳转逻辑）
const handleMenuSelect = (index: any) => {
  activeNav.value = index
  // 实际项目可添加路由跳转：如 router.push(`/${index}`)
}

const handleUserCommand = (command: string) => {
  if (command === 'profile') {
    handlePersonalSettings()
  } else if (command === 'logout') {
    handleLogout()
  }
}

const handlePersonalSettings = () => {
  router.push('/GetUserIdView')
}

const fetchUserProfile = async () => {
  const userId = localStorage.getItem('userid')
  if (!userId) return
  try {
    const { data } = await axios.get(`${READ_BASE_URL}/api/RBAC/GetUserId`, {
      params: { userid: userId }
    })
    if (data?.code === 1) {
      userName.value =
        data?.data?.username ||
        data?.data?.accountname ||
        ''
      userRole.value = data?.data?.rolename || ''
      userAvatar.value = data?.data?.avatar || ''
    }
  } catch (error) {
    console.error('fetch user info error', error)
  }
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '退出',
      cancelButtonText: '取消',
      type: 'warning'
    })
    localStorage.removeItem('userid')
    router.push('/')
  } catch {
    // 用户取消
  }
}
</script>

<style scoped>
.ysjf-home {
  width: 100%;
  height: 100vh;
  min-height: 100vh;
  max-height: 100vh;
  background: #f5f7fb;
  display: flex;
  overflow: hidden;
}

.sidebar {
  background: linear-gradient(180deg, #273c75, #192a56);
  color: #cbd5f5;
  display: flex;
  flex-direction: column;
  padding: 24px 16px;
  box-shadow: 4px 0 12px rgba(25, 42, 86, 0.35);
  height: 100vh;
  max-height: 100vh;
  overflow: hidden;
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #fff;
  margin-bottom: 24px;
}

.logo-icon {
  font-size: 20px;
}

.menu-section {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 4px;

  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-track {
    background: linear-gradient(180deg, #273c75, #192a56);
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.25);
    border-radius: 4px;
  }
}

.nav-menu {
  border-right: none;
  background-color: transparent;
}

.nav-menu :deep(.el-menu-item),
.nav-menu :deep(.el-sub-menu__title) {
  border-radius: 6px;
  margin: 4px 0;
}

.nav-menu :deep(.el-menu-item.is-active) {
  background: rgba(255, 255, 255, 0.15);
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2);
}

.menu-icon {
  margin-right: 8px;
}

.content-container {
  flex: 1;
  height: 100vh;
  min-height: 100vh;
  max-height: 100vh;
  background: linear-gradient(180deg, #eef1f6, #f9fbff);
  margin-left: 260px; /* 为固定侧边栏留出空间 */
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
}

.header {
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 12px 30px rgba(68, 89, 119, 0.08);
  border-bottom: 1px solid rgba(255, 255, 255, 0.4);
  backdrop-filter: blur(14px);
  position: sticky;
  top: 0;
  z-index: 10;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 72px;
  padding: 0 32px;
  border-radius: 16px;
}

.page-title {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.page-title :deep(.el-breadcrumb) {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-title :deep(.el-breadcrumb__item) {
  display: flex;
  align-items: center;
  position: relative;
}

.page-title :deep(.el-breadcrumb__item:not(:last-child)::after) {
  content: '';
  display: inline-block;
  width: 18px;
  height: 2px;
  border-radius: 999px;
  background: linear-gradient(
    90deg,
    rgba(194, 204, 233, 0.8),
    rgba(135, 160, 220, 0.8)
  );
  margin-left: 12px;
}

.breadcrumb-chip {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 14px;
  border-radius: 999px;
  font-weight: 600;
  color: #4a5b7d;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(58, 122, 254, 0.15);
  box-shadow: 0 8px 18px rgba(67, 103, 174, 0.12);
  transition: all 0.2s ease;
}

.breadcrumb-chip:not(.is-current):hover {
  color: #3a7afe;
  border-color: rgba(58, 122, 254, 0.35);
  box-shadow: 0 12px 30px rgba(58, 122, 254, 0.18);
}

.breadcrumb-chip.is-current {
  background: linear-gradient(125deg, #3a7afe, #7c5cfa);
  color: #fff;
  border-color: transparent;
  box-shadow: 0 18px 38px rgba(58, 122, 254, 0.35);
}

.breadcrumb-icon {
  display: inline-flex;
  font-size: 14px;
}

.welcome-text {
  margin: 0;
  color: #909399;
  font-size: 13px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-chip {
  display: inline-flex;
  align-items: center;
  gap: 12px;
  padding: 6px 12px 6px 6px;
  border-radius: 50px;
  background: rgba(255, 255, 255, 0.95);
  color: #2c3e50;
  font-weight: 500;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(148, 163, 184, 0.15);
  transition: all 0.3s ease;

  &:hover {
    background: #fff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
    transform: translateY(-1px);
  }

  .avatar-circle {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 16px;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.4);
    position: relative;
    overflow: hidden;
    flex-shrink: 0;

    .avatar-text {
      font-size: 16px;
      font-weight: 600;
      line-height: 1;
    }

    .avatar-img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 50%;
    }

    .avatar-icon {
      font-size: 20px;
    }

    &::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      border-radius: 50%;
      border: 2px solid rgba(255, 255, 255, 0.3);
      pointer-events: none;
    }
  }

  .user-name {
    font-size: 14px;
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.dropdown-arrow {
  margin-left: 4px;
  font-size: 12px;
  transition: transform 0.3s ease;
  color: #64748b;
}

.user-chip:hover .dropdown-arrow {
  transform: translateY(1px);
}

/* 下拉菜单样式优化 */
:deep(.user-dropdown-menu) {
  padding: 8px;
  min-width: 220px;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  border: 1px solid rgba(148, 163, 184, 0.15);

  .dropdown-header {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px;
    margin-bottom: 4px;
    border-radius: 8px;
    background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%);
    border-bottom: 1px solid rgba(148, 163, 184, 0.1);

    .dropdown-avatar {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 20px;
      font-weight: 600;
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
      flex-shrink: 0;
      position: relative;
      overflow: hidden;

      .avatar-text {
        font-size: 20px;
        font-weight: 600;
        line-height: 1;
      }

      .avatar-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 50%;
      }

      .avatar-icon {
        font-size: 24px;
      }
    }

    .dropdown-user-info {
      flex: 1;
      min-width: 0;

      .dropdown-username {
        font-size: 15px;
        font-weight: 600;
        color: #1e293b;
        margin-bottom: 4px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .dropdown-user-role {
        font-size: 12px;
        color: #64748b;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .dropdown-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 12px;
    border-radius: 6px;
    transition: all 0.2s ease;
    margin: 2px 0;

    .item-icon {
      font-size: 16px;
      color: #64748b;
    }

    &:hover {
      background: #f1f5f9;
      color: #3b82f6;

      .item-icon {
        color: #3b82f6;
      }
    }

    &.logout-item {
      color: #ef4444;

      .item-icon {
        color: #ef4444;
      }

      &:hover {
        background: #fef2f2;
        color: #dc2626;

        .item-icon {
          color: #dc2626;
        }
      }
    }
  }
}

.search-input {
  width: 220px;
}

.el-main {
  padding: 32px;
  background: transparent;
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  height: 100%;
}

.content-wrapper {
  min-height: calc(100vh - 120px);
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 30px 80px rgba(83, 112, 182, 0.12);
  padding: 32px;
  border: 1px solid rgba(255, 255, 255, 0.6);
}
</style>